package cn.lanqiao.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import cn.lanqiao.dao.CourseDao;
import cn.lanqiao.entity.Course;
import cn.lanqiao.util.JdbcUtil;

public class CourseDaoImpl implements CourseDao {

	@Override
	public Object[][] getAllCourse() {
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement ps =null;
		ResultSet rs =null;
		int count = this.count();
		Object[][] datas=new Object[count][];
		String sql="select * from edu_course";
		try {
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery();
			for(int i=0;rs.next();i++) {
				datas[i] =new Object[] {rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)};
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(rs, ps, conn);
		}
		
		return datas;
	}

	@Override
	public int count() {
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement ps =null;
		ResultSet rs =null;
		String sql="select count(*) from edu_course";
		int num = 0;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()) {
				num = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(rs, ps, conn);
		}
		return num;
	}
   //删除课程
	public void deleteCourseByid(String id) {
		Connection conn=JdbcUtil.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="delete from edu_course where cid=?";		
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, id);
			rs=ps.executeQuery();
			
			
		} catch (SQLException e) {

			e.printStackTrace();
		}finally {
			JdbcUtil.close(rs, ps, conn);
		}
	}
	//修改课程
	public void updateCourse(String id,Course course) {
		Connection conn=JdbcUtil.getConnection();
		PreparedStatement ps=null;
		//找到修改的元素
		String sql="update edu_course set cname=?,cteacher=?,cexam=? where cid=?";
		
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, course.getCname());
			ps.setString(2, course.getCteaher());
			ps.setString(3, course.getCexam());
			ps.setString(4, id);
			
			ps.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(null, null, conn);
		}
		
		
	}
	//添加课程
	public int addCourse(Course course) {
		Connection conn=JdbcUtil.getConnection();
		PreparedStatement ps=null;

		int values=0;
		String sql="insert into edu_course values (?,?,?,?,?)";
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1,UUID.randomUUID().toString());
			ps.setString(2, course.getCid());
			ps.setString(3, course.getCname());
			ps.setString(4, course.getCteaher());
			ps.setString(5, course.getCexam());
			ps.executeUpdate();
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(null, ps, conn);
		}
			
		return values;
	}
	}

